const express = require('express')
const multer = require('multer')
const fs = require('fs')
const db = require('../../db')
const router = express.Router()
const path = require('path')

const UPLOAD_DIR = path.join(__dirname, 'uploads', 'avatar')

if (!fs.existsSync(UPLOAD_DIR)) fs.mkdirSync(UPLOAD_DIR)

const Upload = multer({
  storage: multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, UPLOAD_DIR)
    },
    filename: (req, file, cb) => {
      const { uploadId } = req.query
      const ext = file.mimetype.split('/')[1]
      req.avatar_url = `avatar-${uploadId}-${Date.now()}.${ext}`
      cb(null, req.avatar_url)
    }
  }),
  limits: {
    fileSize: 1024 * 1024 * 100
  }
})

router.post('/', Upload.single('file'), (req, res) => {
  const { uploadId } = req.query
  // console.log(req.query)

  const avatar_url = 'http://127.0.0.1:9091/setting/download/avatar/' + req.avatar_url

  const setData = 'update easy_chat.users set avatar_url = ? where wx_id = ?'
  db.query(setData, [avatar_url, uploadId], (err, result) => {
    if (err) res.errHandle(err)
    // console.log(result)

    res.send({
      code: 200,
      message: 'success',
      data: {
        uploadId,
        avatar_url,
        message: '设置成功'
      }
    })
  })
})

module.exports = router
